package com.moive.news.tqnewsapplication.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.adapter.JiudiandelAdapter;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.DyReleaseEntity;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.photo.PhotoPickerActivity;
import com.moive.news.tqnewsapplication.photo.utils.ImageLoader;
import com.moive.news.tqnewsapplication.photo.utils.LogUtils;
import com.moive.news.tqnewsapplication.photo.utils.OtherUtils;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsManager;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsResultAction;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.MyGridView;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.TimeUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.upyun.library.common.Params;
import com.upyun.library.common.UploadEngine;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;
import com.upyun.library.utils.UpYunUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.moive.news.tqnewsapplication.networks.BaseApi.BASEUR_IMG;
import static com.moive.news.tqnewsapplication.networks.BaseApi.PASSWORD;

/**
 * Created by Administrator on 2017/12/20.
 */

public class PutNewsActivity extends BaseActivity {
    @BindView(R.id.putnews_back)
    ImageView putnewsBack;
    @BindView(R.id.aaaaa)
    TextView aaaaa;
    @BindView(R.id.putnews_type)
    TextView putnewsType;
    @BindView(R.id.punew_ll)
    RelativeLayout punewLl;
    @BindView(R.id.punews_edit)
    EditText punewsEdit;
    @BindView(R.id.title_edit)
    EditText titleEdit;
    @BindView(R.id.upnews_button)
    Button upnewsButton;

    @BindView(R.id.addImg)
    ImageView addImg;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    @BindView(R.id.releaseGridView)
    MyGridView releaseGridView;
    private String userimgurl = "";
    // 屏幕的width
    private int mScreenWidth;
    // 屏幕的height
    private int mScreenHeight;
    private View contentView;
    PopupWindow popupWindow;
    private List<String> list = new ArrayList<>();
    JiudiandelAdapter ad;
    private int MAX_LENGTH = 200;
    private int MAX_PIC_LENGTH = 9;

    private static final int PICK_PHOTO = 1;
    private List<String> mResults = new ArrayList<>();
    private GridAdapter mAdapter;
    private GridAdapter gridAdapter;
    private List<DyReleaseEntity> dyReleaseEntityList = new ArrayList<>();
    private int mColumnWidth;
    private Gson gson = new Gson();
    String comment1 = "";
    public final static int REQUEST_READ_PHONE_STATE = 1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_putnews);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        list.add("糗事");
        int screenWidth = OtherUtils.getWidthInPx(getApplicationContext());
        mColumnWidth = (screenWidth - OtherUtils.dip2px(getApplicationContext(), 4)) / 3;
        dyReleaseEntityList.clear();
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("1");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        gridAdapter = new GridAdapter(dyReleaseEntityList);
        releaseGridView.setAdapter(gridAdapter);
        gridAdapter.notifyDataSetChanged();
        titleEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 15) {
                    ToastUtils.ShortToast("标题最多发送15个字");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        punewsEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 50) {
      ToastUtils.ShortToast("正文内容最多50个字");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.putnews_back, R.id.punew_ll, R.id.upnews_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.putnews_back:
                finish();
                break;
            case R.id.punew_ll:
                showpopwinds();
                backgroundAlpha(0.7f);
                break;
            case R.id.upnews_button:
                upnews();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                showResult(result);
            }
        }
    }

    private void showResult(ArrayList<String> paths) {
        mResults.clear();
        dyReleaseEntityList.clear();
        gridAdapter.notifyDataSetChanged();
        for (int i = 0; i < paths.size(); i++) {
            DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
            dyReleaseEntity.setImgPath(paths.get(i));
            dyReleaseEntity.setImgType("1");
            dyReleaseEntityList.add(dyReleaseEntity);
//            mResults.add(paths.get(i));
        }
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("2");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        if (mAdapter == null) {
            mAdapter = new GridAdapter(dyReleaseEntityList);
        }
        releaseGridView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        if (dyReleaseEntityList.size() > 8) {
            dyReleaseEntityList.remove(9);
        }
        //上传图片
        upimg();
    }

    private void upimg() {
        final Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET, BaseApi.SPACE);
        //保存路径，任选其中一个
        //        dyReleaseEntityList
        String date = TimeUtil.parseDate(new Date().getTime());
        for (int i = 0; i < dyReleaseEntityList.size() - 1; i++) {
            File file = null;
            String filepath = dyReleaseEntityList.get(i).getImgPath();
            LogUtil.i("lidaming", filepath);
            String geshi = filepath.substring(filepath.lastIndexOf("."));
            String savePath = "/uploads/" + date + "/" + UUID.randomUUID().toString().replaceAll("-", "") + geshi;
            file = new File(filepath);
            //表单上传（本地签名方式）
            paramsMap.put(Params.SAVE_KEY, savePath);
            UploadEngine.getInstance().formUpload(file, paramsMap, BaseApi.OPERATER, UpYunUtils.md5(PASSWORD), completeListener, progressListener);
        }
    }

    //结束回调，不可为空
    UpCompleteListener completeListener = new UpCompleteListener() {
        @Override
        public void onComplete(boolean isSuccess, String result) {
            Log.e(TAG, isSuccess + ":" + result);
            if (isSuccess == true) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    userimgurl = jsonObject.getString("url");
                    ToastUtils.ShortToast("上传图片成功！");
                    mResults.add(BASEUR_IMG + userimgurl);
                    LogUtils.e("lidaming", "userimgurl=" + BASEUR_IMG + userimgurl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                ToastUtils.ShortToast("上传图片失败！");
            }
        }
    };
    //进度回调，可为空
    UpProgressListener progressListener = new UpProgressListener() {
        @Override
        public void onRequestProgress(final long bytesWrite, final long contentLength) {
//            uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
//            textView.setText((100 * bytesWrite) / contentLength + "%");
            Log.e(TAG, (100 * bytesWrite) / contentLength + "%");
            Log.e(TAG, bytesWrite + "::" + contentLength);
        }
    };

    //显示分类类别
    private void showpopwinds() {
        mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mScreenHeight = getWindowManager().getDefaultDisplay().getHeight();
        contentView = getLayoutInflater().inflate(R.layout.putnews_hudu, null);
        ImageView buss_pop_quxiao = (ImageView) contentView.findViewById(R.id.buss_pop_quxiao);
        RecyclerView more_server = contentView.findViewById(R.id.more_server);
        popupWindow = new PopupWindow(contentView, mScreenWidth * 9 / 10, WindowManager.LayoutParams.WRAP_CONTENT, true);
        //        设置popwindow如果点击外面区域，便关闭。
        popupWindow.setOutsideTouchable(true);
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.update();
        buss_pop_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        ad = new JiudiandelAdapter(PutNewsActivity.this, list);
        more_server.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        more_server.setAdapter(ad);
        ad.setOnItemActionListener(new JiudiandelAdapter.OnItemActionListener() {
            @Override
            public void onItemClickListener(View v, int pos) {
                putnewsType.setText(list.get(pos));
                popupWindow.dismiss();
            }
        });
//        backgroundAlpha(0.7f);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.2f;
        getWindow().setAttributes(lp);
        //添加pop窗口关闭事件
        popupWindow.setOnDismissListener(new poponDismissListener());
    }

    /**
     * 添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    //上传新闻
    private void upnews() {
        String token = PreferenceUtil.getString("token", "");
        String category = putnewsType.getText().toString().trim();
        String comment = punewsEdit.getText().toString().trim();
        String title = titleEdit.getText().toString().trim();
        if (TextUtils.isEmpty(category)){
            ToastUtils.ShortToast("请选择投稿类型！");
            return;
        }
        if (TextUtils.isEmpty(userimgurl)) {
            ToastUtils.ShortToast("请上传图片！");
            return;
        }
        String jsonArray = gson.toJson(mResults.toArray());
        try {
            comment1 = URLEncoder.encode(comment, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OkHttpUtils.post()
                .url(BaseApi.PUTNEWS)
                .addParams("token", token)
                .addParams("title", title)
                .addParams("content", comment1)
                .addParams("imgs", jsonArray)
                .addParams("category", category)
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        ToastUtils.ShortToast("上传成功！");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                finish();
                            }
                        }, 2000);

                    } else {
                        ToastUtils.ShortToast("上传失败!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class GridAdapter extends BaseAdapter {
        private List<DyReleaseEntity> pathList;

        public GridAdapter(List<DyReleaseEntity> pathList) {
            this.pathList = pathList;
        }

        @Override
        public int getCount() {
            return pathList.size();
        }

        @Override
        public Object getItem(int position) {
            return pathList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mColumnWidth, mColumnWidth);
                holder.imageView.setLayoutParams(params);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (pathList.get(position).getImgType().equals("2")) {
                holder.imageView.setBackgroundResource(R.drawable.add02);
                holder.imageView.setEnabled(true);
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        Intent intent = new Intent(PutNewsActivity.this, PhotoPickerActivity.class);
//                        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
//                        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
//                        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, MAX_PIC_LENGTH);
//                        startActivityForResult(intent, PICK_PHOTO);
                        check();
                    }
                });
            } else {
                ImageLoader.getInstance().display(pathList.get(position).getImgPath(), holder.imageView, mColumnWidth, mColumnWidth);
                holder.imageView.setEnabled(false);
            }
            return convertView;
        }

        private class ViewHolder {
            public ImageView imageView;
        }
    }
    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(PutNewsActivity.this,new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                go();
            }
            @Override
            public void onDenied(String permission) {
             ToastUtils.ShortToast("用户拒绝授权");
            }
        });



    }
    private void go(){
        Intent intent = new Intent(PutNewsActivity.this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, MAX_PIC_LENGTH);
        startActivityForResult(intent, PICK_PHOTO);
    }
}
